/**
 * @Author:金雅蓓
 * @LastEditors: 金雅蓓
 * @Description:处理数组为树状结构
 * @param {Array} data 获取到的一维数组
 * @param {string} key 用于对比的key
 */
function convertListToTree(data, key) {
  const result = [];
  const map = {};
  if (Array.isArray(data) && data.length > 0) {
    data.forEach((item) => {
      map[item.id] = item;
    });
    data.forEach((item) => {
      const parent = map[item[key]];
      if (parent) {
        (parent.children || (parent.children = [])).push(item);
      } else {
        result.push(item);
      }
    });
  }
  return result;
}

/**
 * @Author:金雅蓓
 * @LastEditors: 金雅蓓
 * @Description:获取同级的下一节点或者下一节点
 * @param {Array} nodeList 树状结构
 * @param {Object} node 当前节点
 * @param {string} type 移动类型
 * @param {string} key 用于对比的key
 */
function getBeforeOrAfterNode(nodeList, node, type, key) {
  const levelIdList = [];
  for (let i = 0; i < nodeList.length; i++) {
    if (node[key] == nodeList[i][key]) {
      levelIdList.push(nodeList[i].id);
    }
  }
  const index = levelIdList.findIndex((item) => item == node.id);
  return type == "bottom" ? levelIdList[index + 1] : type == "top" ? levelIdList[index - 1] : "";
}

/**
 * @Author:金雅蓓
 * @LastEditors: 金雅蓓
 * @Description: 判断节点处理树的位置，用来显示移动按钮
 * @param {Array} nodeList 树状结构
 * @param {Number} id 当前节点的id
 * @param {String} type 移动类型
 */
function handleShowMoveButton(nodeList, id, type) {
  const { children } = nodeList;
  if (Array.isArray(children) && children.length > 0) {
    const idList = [];
    for (let i = 0; i < children.length; i++) {
      idList.push(children[i].id);
    }
    if (idList.length == 1) return false;
    const index = idList.findIndex((item) => item == id);
    if (index == 0) {
      return type == "bottom";
    } else if (index == idList.length - 1) {
      return type == "top";
    } else {
      return type == "top" || type == "bottom";
    }
  } else {
    return false;
  }
}

function treeToArr(data) {
  const arr = [];
  while (data.length > 0) {
    const record = data.shift();
    if (Array.isArray(record.children) && record.children.length > 0) {
      data.push(...record.children);
      delete record.children;
    }
    arr.push(record);
  }
  return arr;
}

module.exports = {
  convertListToTree,
  getBeforeOrAfterNode,
  handleShowMoveButton,
  treeToArr,
};
